const pool = require('../config/database');

// 获取平台统计信息
const getPlatformStats = async (req, res) => {
  try {
    // 总车辆数
    const [carCount] = await pool.execute(
      'SELECT COUNT(*) as count FROM cars WHERE status = "approved"'
    );

    // 总用户数
    const [userCount] = await pool.execute('SELECT COUNT(*) as count FROM users');

    // 今日新增车辆
    const [todayCars] = await pool.execute(
      'SELECT COUNT(*) as count FROM cars WHERE DATE(created_at) = CURDATE()'
    );

    // 热门品牌
    const [popularBrands] = await pool.execute(
      `SELECT brand, COUNT(*) as count 
       FROM cars 
       WHERE status = "approved" 
       GROUP BY brand 
       ORDER BY count DESC 
       LIMIT 5`
    );

    res.json({
      totalCars: carCount[0].count,
      totalUsers: userCount[0].count,
      todayNewCars: todayCars[0].count,
      popularBrands: popularBrands.map(item => ({
        brand: item.brand,
        count: item.count
      }))
    });
  } catch (error) {
    console.error('获取平台统计错误:', error);
    res.status(500).json({ message: '服务器错误' });
  }
};

// 获取用户统计信息
const getUserStats = async (req, res) => {
  try {
    const userId = req.user.userId;

    // 用户发布的车辆数
    const [userCars] = await pool.execute(
      'SELECT COUNT(*) as count FROM cars WHERE seller_id = ?',
      [userId]
    );

    // 用户收藏数
    const [favoritesCount] = await pool.execute(
      'SELECT COUNT(*) as count FROM favorites WHERE user_id = ?',
      [userId]
    );

    // 用户车辆浏览数（需要浏览记录表）
    const [viewsCount] = await pool.execute(
      'SELECT COUNT(*) as count FROM car_views WHERE user_id = ?',
      [userId]
    );

    res.json({
      publishedCars: userCars[0].count,
      favoritesCount: favoritesCount[0].count,
      viewsCount: viewsCount[0].count || 0
    });
  } catch (error) {
    console.error('获取用户统计错误:', error);
    res.status(500).json({ message: '服务器错误' });
  }
};

module.exports = {
  getPlatformStats,
  getUserStats
};